import { ref, onMounted, onBeforeUnmount, reactive } from 'vue'

export const useResizeObserver = () => {
  const domRef = ref<HTMLElement | null>(null)
  const sizeInfo = reactive({ width: 0, height: 0 })
  const resizeObserver = ref<ResizeObserver | null>(null)

  const createResizeObserver = (parentElement: HTMLElement) => {
    resizeObserver.value = new ResizeObserver((entries) => {
      for (const entry of entries) {
        sizeInfo.width = entry.contentRect.width
        sizeInfo.height = entry.contentRect.height
      }
    })
    resizeObserver.value.observe(parentElement)
  }

  const disconnectResizeObserver = () => {
    if (resizeObserver.value) {
      resizeObserver.value.disconnect()
    }
  }

  onMounted(() => {
    if (domRef.value && 'ResizeObserver' in window) {
      createResizeObserver(domRef.value)
    }
  })

  onBeforeUnmount(() => {
    disconnectResizeObserver()
  })

  return {
    domRef,
    sizeInfo,
  }
}
